import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pattern_lock/pattern_lock.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../service/SynDataService.dart';
import '../../../../util/DbUtil.dart';
import '../../../../util/ImConstant.dart';
import '../../../../util/Md5Util.dart';
import '../../../bloc/LoginCubit.dart';
import '../UiUtil.dart';

class PatternLockView extends StatelessWidget {
  final String tenantCode;
  final String loginSuccessUrl;

  const PatternLockView({required this.tenantCode, required this.loginSuccessUrl, super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 30, right: 30),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 20, bottom: 10),
            child: _buildLoginingPane(context),
          ),
          SizedBox(
            width: 300,
            height: 300,
            child: PatternLock(
              // color of selected points.
              selectedColor: Colors.blue,
              // radius of points.
              pointRadius: 20,
              // whether show user's input and highlight selected points.
              showInput: true,
              // count of points horizontally and vertically.
              dimension: 3,
              // padding of points area relative to distance between points.
              relativePadding: 0.7,
              // needed distance from input to point to select point.
              selectThreshold: 25,
              // whether fill points.
              fillPoints: true,
              // callback that called when user's input complete. Called if user selected one or more points.
              onInputComplete: (List<int> input) {
                print("pattern is $input");
                String password = input.join();
                login(context, password);
              },
            ),
          )
        ],
      ),
    );
  }

  Widget _buildLoginingPane(BuildContext context) {
    final state = context.watch<LoginCubit>().state;
    return Visibility(
      visible: state.msg != '',
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 80,
            child: buildSvgView('assets/svg/error.svg', 30, 30, Colors.red),
          ),
          SizedBox(
            width: 150,
            child: Text(state.msg),
          )
        ],
      ),
    );
  }

  login(BuildContext context, String password) async {
    LoginCubit loginCubit = context.read<LoginCubit>();

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(ImConstant.IM_PATTERN_LOCK_SETTING, true);
    String md5Password = generateMd5(password);
    String? dbPassword = prefs.getString(ImConstant.IM_PATTERN_LOCK_PASSWORD);
    String? dbUserid = prefs.getString(ImConstant.IM_PATTERN_LOCK_USERID);
    if (md5Password == dbPassword && dbUserid != null) {
      loginCubit.loginBySlide(dbUserid!, md5Password, this.tenantCode, 'android-flutter').then((loginResp) async {

        SynDataService synDataService = SynDataService();
        await synDataService.synData(dbUserid);

        Navigator.of(context).pushNamed(this.loginSuccessUrl);
      });
    }
  }
}
